<template>
  <div class="full-box overflow-hidden d-flex">
    <div class="left-tab d-flex-c">
      <div
        :class="['left-tab-item d-flex-c ai-c jc-c c-pointer f-14', currentLeftTab === key ? 'active' : '']"
        v-for="(item, key) in leftTabs"
        :key="key"
        @click="clickLeftTab(key)"
      >
        <span class="text">{{ item }}</span>
      </div>
    </div>
    <div class="flex-1 overflow-hidden d-flex-c">
      <div class="d-flex p-h-mini p-t-mini">
        <el-cascader
          v-model="currentCity"
          :options="regionTree"
          size="small"
          class="m-r-mini"
          :props="{ checkStrictly: true, multiple: true }"
          clearable
        />
        <BKSelect
          v-model="selectValue"
          size="small"
          class="m-r-mini"
          style="width: 150px;"
          placeholder="请选择水库类型"
          v-if="currentLeftTab === '2'"
          dictionary-key="SKLX"
          clearable
        />
        <BKInput
          v-model="keywords"
          size="small"
          class="m-r-mini"
          style="width: 200px;"
          :placeholder="placeholder"
          clearable
        />
        <el-button
          size="small"
          type="primary"
          @click="search()"
        >
          搜索
        </el-button>
      </div>
      <div class="flex-1 overflow-hidden">
        <ConfigGrid
          :configs="configs[i]"
          v-show="currentLeftTab === i.toString()"
          :ref="'grid' + i"
          v-for="(item, i) in configs"
          :key="i"
          :has-add="false"
          :has-batch-remove="false"
          :has-checkbox="false"
          :before-query="beforeQuery"
        />
      </div>
    </div>
    <ConfigForm
      :configs="formConfigs"
      ref="form"
      :before-submit="beforeSubmit"
      @saveSuccess="saveSuccess"
      @finishLoading="finishLoading"
    />
    <!-- <DictionaryTreeModal
      ref="dictionaryTreeModal"
      button-size="small"
      @select="handleDictionaryTreeSelect"
    /> -->
  </div>
</template>

<script>
const regionMap = {
  0: { metaSet: 'REL_RV_AD', idKey: 'RV_CODE' },
  1: { metaSet: 'REL_LK_AD', idKey: 'LK_CODE' },
  2: { metaSet: 'REL_RES_AD', idKey: 'RES_CODE' },
  3: { metaSet: 'REL_WAGA_AD', idKey: 'WAGA_CODE' },
  4: { metaSet: 'REL_PUST_AD', idKey: 'PUST_CODE' },
  5: { metaSet: 'REL_FSDA_AD', idKey: 'FSDA_CODE' },
  6: { metaSet: 'REL_DIKE_AD', idKey: 'DIKE_CODE' },
  7: { metaSet: 'REL_XHRV_AD', idKey: 'XHRV_CODE' },
  8: { metaSet: 'REL_RUDA_AD', idKey: 'RUDA_CODE' },
  9: { metaSet: 'REL_PIVOT_AD', idKey: 'PIVOT_CODE' }
}
export default {
  name: 'ItemPanel',
  components: {
  },
  data () {
    return {
      currentLeftTab: '0',
      leftTabs: {
        0: '河流',
        1: '湖泊',
        2: '水库',
        3: '水闸',
        4: '泵站',
        5: '蓄滞洪区',
        6: '堤防',
        7: '行洪河道',
        8: '橡胶坝',
        9: '枢纽'
      },
      configs: {
        0: {
          metaSet: 'ATT_RV_BASE',
          appId: 'YSJC',
          bzCode: 'YSJC',
          module: '河流',
          noOperation: true,
          afterFetchColumns: this.afterFetchColumns,
          gridMethod: 'select_rvList'
        },
        1: {
          metaSet: 'ATT_LK_BASE',
          appId: 'YSJC',
          bzCode: 'YSJC',
          module: '湖泊',
          noOperation: true,
          afterFetchColumns: this.afterFetchColumns,
          gridMethod: 'select_lkList'
        },
        2: {
          metaSet: 'ATT_RES_BASE',
          appId: 'YSJC',
          bzCode: 'YSJC',
          module: '水库',
          noOperation: true,
          afterFetchColumns: this.afterFetchColumns,
          gridMethod: 'select_resList'
        },
        3: {
          metaSet: 'ATT_WAGA_BASE',
          appId: 'YSJC',
          bzCode: 'YSJC',
          module: '水闸',
          noOperation: true,
          afterFetchColumns: this.afterFetchColumns,
          gridMethod: 'select_wagaList'
        },
        4: {
          metaSet: 'ATT_PUST_BASE',
          appId: 'YSJC',
          bzCode: 'YSJC',
          module: '泵站',
          noOperation: true,
          afterFetchColumns: this.afterFetchColumns,
          gridMethod: 'select_pustList'
        },
        5: {
          metaSet: 'ATT_FSDA_BASE',
          appId: 'YSJC',
          bzCode: 'YSJC',
          module: '蓄滞洪区',
          noOperation: true,
          afterFetchColumns: this.afterFetchColumns,
          gridMethod: 'select_fsdaList'
        },
        6: {
          metaSet: 'ATT_DIKE_BASE',
          appId: 'YSJC',
          bzCode: 'YSJC',
          module: '堤防',
          noOperation: true,
          afterFetchColumns: this.afterFetchColumns,
          gridMethod: 'select_dikeList'
        },
        7: {
          metaSet: 'ATT_XHRV_BASE',
          appId: 'YSJC',
          bzCode: 'YSJC',
          module: '行洪河道',
          noOperation: true,
          afterFetchColumns: this.afterFetchColumns,
          gridMethod: 'select_xhrvList'
        },
        8: {
          metaSet: 'ATT_RUDA_BASE',
          appId: 'YSJC',
          bzCode: 'YSJC',
          module: '橡胶坝',
          noOperation: true,
          afterFetchColumns: this.afterFetchColumns,
          gridMethod: 'select_rudaList'
        },
        9: {
          metaSet: 'ATT_PIVOT_BASE',
          appId: 'YSJC',
          bzCode: 'YSJC',
          module: '枢纽',
          noOperation: true,
          afterFetchColumns: this.afterFetchColumns,
          gridMethod: 'select_pivotList'
        }
      },
      regionTree: [],
      currentCity: [],
      selectValue: '',
      keywords: ''
    }
  },
  computed: {
    formConfigs () {
      return {
        ...this.configs[this.currentLeftTab],
        formItemProcessor: this.formItemProcessor,
        modal: {
          width: 800,
          transfer: true
        }
      }
    },
    placeholder () {
      if (this.type) {
        return '请输入站点名称或站点编号'
      } else {
        return this.currentLeftTab === '2' ? '请输入水库名称或站码' : '请输入名称'
      }
    }
  },
  async created () {
    this.regionTree = await this.getRegionTree()
  },
  mounted () {
    this.$refs.grid0[0].refreshList({})
  },
  methods: {
    clickLeftTab (key) {
      this.currentLeftTab = key
      this.$refs['grid' + key][0].refreshList({})
    },
    search () {
      this.$refs['grid' + this.currentLeftTab][0].refreshList({})
    },
    afterFetchColumns (columns) {
      columns.push({
        title: '操作',
        width: 80,
        fixed: 'right',
        slots: {
          default: ({ row }) => {
            return [
              <div class="operation-icon-buttons">
                <i class="el-icon-edit" title="编辑" onClick={() => { this.editRow(row) }}></i>
              </div>
            ]
          }
        }
      })
      return columns
    },
    editRow (row) {
      this.$refs.form.show(row, true)
    },
    beforeSubmit (data) {
      return {
        appId: this.configs[this.currentLeftTab].appId,
        bzCode: this.configs[this.currentLeftTab].bzCode,
        metaSet: this.configs[this.currentLeftTab].metaSet,
        methodCode: 'update',
        methodParams: JSON.stringify(data)
      }
    },
    async finishLoading (form) {
      const formData = form.getFormData()
      const { rows } = await this.$request.singleTableOperation({
        url: '/grid/getTableData',
        metaSet: regionMap[this.currentLeftTab].metaSet,
        methodCode: 'select',
        methodParams: { queryParam: { [regionMap[this.currentLeftTab].idKey]: formData[regionMap[this.currentLeftTab].idKey] } }
      })

      const arr = []
      for (const item of rows) {
        arr.push([item.CITY_CODE, item.COUN_CODE])
      }
      form.setFormData({ region: arr })
      // this.$refs.form.$refs.form.setDictionaryInput('region', {
      //   value: option.value.join(','),
      //   text: option.label.join(',')
      // })
    },
    formItemProcessor ({ items, rules }) {
      items.push({
        label: '行政区',
        group: '可编辑表单',
        labelWidth: items[0].labelWidth,
        field: 'region',
        type: 'el-cascader',
        itemClass: 'region',
        props: { filterable: true, props: { multiple: true }, options: this.regionTree }
      })
      return { items, rules }
    },
    async saveSuccess (e, { form }) {
      const formData = JSON.parse(form.methodParams)
      const arr = formData.region.split(',')
      const result = []
      if (arr.length && arr[0]) {
        for (let i = 0; i < arr.length; i = i + 2) {
          result.push([arr[i], arr[i + 1]])
        }
      }
      if (!result.length) return
      await this.$request.singleTableOperation({
        metaSet: regionMap[this.currentLeftTab].metaSet,
        methodCode: 'override',
        methodParams: {
          deleteParam: { [regionMap[this.currentLeftTab].idKey]: formData[regionMap[this.currentLeftTab].idKey] },
          batchParam: result.map(item => ({
            [regionMap[this.currentLeftTab].idKey]: formData[regionMap[this.currentLeftTab].idKey],
            PRO_CODE: '130000',
            CITY_CODE: item[0],
            COUN_CODE: item[1]
          }))
        }
      })
    },
    // clickHandler () {
    //   const formData = this.$refs.form.$refs.form.getFormData()
    //   this.$refs.dictionaryTreeModal.show({ dictionaryKey: 'YSQJC_JC_XZQ', isMultiple: '1', props: { checkStrictly: false }, field: 'region' }, formData)
    // },
    // async handleDictionaryTreeSelect (option) {
    //   this.regionData = await this.recurseRegionData(option.value)
    //   this.$refs.form.$refs.form.setDictionaryInput('region', {
    //     value: option.value,
    //     text: option.label
    //   })
    // },
    // async recurseRegionData (value) {
    //   const data = await this.$utils.dictionary.getOptionsByKey('YSQJC_JC_XZQ')
    //   let arr = []
    //   function handler (value) {
    //     const node = data.find(d => d.value === value)
    //     arr.push(node.value)
    //     const parent = data.find(item => item.value === node.fcode)
    //     if (parent) {
    //       return handler(parent.value)
    //     }
    //     if (arr.length > 1) {
    //       const temp = [...arr]
    //       arr = []
    //       return temp.reverse()
    //     }
    //     return arr.reverse()
    //   }
    //   return value.split(',').map(item => item ? handler(item) : item)
    // },
    async getRegionTree () {
      const data = await this.$utils.dictionary.getOptionsByKey('YSQJC_JC_XZQ')
      function handler (id) {
        const arr = data.filter(item => item.fcode === id)
        if (!arr.length) return null
        return arr.map(item => ({
          label: item.label,
          value: item.value,
          children: handler(item.value)
        }))
      }
      return handler('130000')
    },
    beforeQuery (params) {
      params.methodParams = JSON.stringify({
        SJXZQDM: this.currentCity ? this.currentCity.filter(item => item.length === 1).map(item => item[0]).join(',') : '',
        XJXZQDM: this.currentCity ? this.currentCity.filter(item => item.length === 2).map(item => item[1]).join(',') : '',
        NAME: this.keywords,
        SKLX: this.selectValue
      })
      this.$refs['grid' + this.currentLeftTab][0].currentQueryParams = params
      return params
    }
  }
}
</script>

<style lang="scss" scoped>
.left-tab {
  width: 104px;
  background: linear-gradient(0deg, #fff 0%, #f3f6f9 100%);
  border-right: 1px solid #e1e9f0;
  align-items: flex-end;
  padding-top: 17px;

  .left-tab-item {
    width: 92px;
    height: 60px;
    color: #6a6b7f;
    position: relative;

    &.active {
      background: #fff;
      border: 1px solid #e2eaf1;
      border-right: none;
      border-radius: 8px 0 0 8px;
      margin-right: -1px;

      &::before {
        content: "";
        width: 6px;
        height: 60px;
        background: linear-gradient(90deg, #0080ff 0%, #fff 100%);
        border-radius: 6px 0 0 6px;
        display: inline-block;
        position: absolute;
        left: 0;
        top: 0;
      }
    }

    &:hover {
      > .text {
        color: #333;
      }
    }
  }
}

.main-area {
  padding: 0 16px;
}

::v-deep .region {
  .el-cascader {
    width: 100%;
  }
}
</style>
